<?php
declare(strict_types=1);
namespace SixShop\Lakala\Cron;

use SixShop\Core\Attribute\Cron;
use SixShop\Lakala\Service\PaymentRecordService;
use SixShop\Payment\Model\ExtensionPaymentModel;
use SixShop\Wechat\Service\ExpressService;
use think\db\Query;
use think\facade\Db;

class WechatOrderCron
{
    public function __construct(
        private PaymentRecordService $paymentRecordService,
        private ExpressService $expressService,
    )
    {
        $this->expressService->getAllDelivery();
    }

    #[Cron('0 */10 * * * *', 'lakala.shipping')]
    public function orderShipping(): void
    {
        ExtensionPaymentModel::alias('p')
            ->leftJoin('order o', 'o.id = p.order_id')
            ->leftJoin('lakala_wechat_payment w', 'p.id = w.payment_id')
            ->where([
                'p.pay_type' => 'lakala',
                'p.status' => 2,
                'o.shipping_status' => 1
            ])
            ->where(function (Query $query) {
                $query->whereIn('w.order_state', [1,2])
                    ->whereOr('w.order_state', null);
            })
            ->field('p.id,w.order_state')
            ->select()->each(function ($payment){
                if ($payment->order_state === null) {
                    $this->paymentRecordService->createWechatOrder($payment->id);
                }
                $this->paymentRecordService->updateWechatOrder($payment->id);
            });
    }
}